<template>
  <div class="dict-container">
    <base-table
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      :data="tableData"
      :loading="loading"
      :total="total"
      :hide-operation="false"
      @search="handleSearch"
      @reset="handleReset"
      @add="handleAdd"
      @edit="handleEdit"
      @delete="handleDelete"
      @detail="handleDetail"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
    >
      <!-- 搜索区域 -->
      <template #search>
        <el-form>
          <el-form-item label="字典名称">
            <el-input
              v-model="queryParams.baseSystemDictQueryVo.name"
              placeholder="请输入字典名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="字典类型名称">
            <el-input
              v-model="queryParams.baseSystemDictQueryVo.typeName"
              placeholder="请输入字典类型名称"
              clearable
            />
          </el-form-item>
        </el-form>
      </template>

      <!-- 表格列配置 -->
      <el-table-column
        prop="name"
        label="字典名称"
        min-width="120"
      />
      <el-table-column
        prop="value"
        label="字典编码"
        min-width="120"
      />
      <el-table-column
        prop="typeName"
        label="字典类型名称"
        min-width="120"
      />
      <el-table-column
        prop="type"
        label="字典类型编码"
        min-width="120"
      />
      <el-table-column
        prop="parentValue"
        label="父级编码"
        min-width="120"
      />
      <el-table-column
        prop="status"
        label="状态"
        width="66"
      >
        <template #default="{ row }">
          <el-switch
            :model-value="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="(val) => handleStatusChange(row, val)"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="160"
      />
    </base-table>

    <!-- 新增/编辑抽屉 -->
    <drawer-form
      v-model="drawer.visible"
      :title="drawer.title"
      :loading="drawer.loading"
      :rules="drawer.type === 'detail' ? {} : rules"
      :readonly="drawer.type === 'detail'"
      :data="formData"
      @submit="handleSubmit"
    >
      <el-form-item
        label="字典名称"
        prop="name"
      >
        <el-input
          v-model="formData.name"
          placeholder="请输入字典名称"
        />
      </el-form-item>
      <el-form-item
        label="字典编码"
        prop="value"
      >
        <el-input
          v-model="formData.value"
          placeholder="请输入字典编码"
        />
      </el-form-item>
      <el-form-item
        label="字典类型名称"
        prop="type"
      >
        <el-input
          v-model="formData.typeName"
          placeholder="请输入字典类型名称"
        />
      </el-form-item>
      <el-form-item
        label="字典类型编码"
        prop="type"
      >
        <el-input
          v-model="formData.type"
          placeholder="请输入字典类型编码"
        />
      </el-form-item>

      <el-form-item
        label="父级编码"
        prop="parentValue"
      >
        <el-input
          v-model="formData.parentValue"
          placeholder="请输入父级编码"
        />
      </el-form-item>
      <el-form-item
        label="状态"
        prop="status"
      >
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">{{ t('dict.enable') }}</el-radio>
          <el-radio :label="0">{{ t('dict.forbid') }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </drawer-form>
  </div>
</template>

<script setup lang="ts">
  import { API_URLS } from '@/base/interface-config';
  import { axiosRequest } from '@/utils/http-service';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { onMounted, reactive, ref } from 'vue';
  import { useI18n } from 'vue-i18n';

  // 查询参数
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    orderBy: 'create_time desc',
    baseSystemDictQueryVo: {
      name: '',
      typeName: ''
    }
  });

  // 表格数据
  const tableData = ref([]);
  const total = ref(0);
  const loading = ref(false);

  // 抽屉表单
  const drawer = reactive({
    visible: false,
    title: '',
    loading: false,
    type: '' // 新增: add, 编辑: edit, 详情: detail
  });

  // 表单数据
  const formData = reactive({
    dataDictId: '',
    name: '',
    value: '',
    parentValue: '',
    type: '',
    typeName: '',
    status: 1
  });

  // 表单校验规则
  const rules = {
    name: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
    value: [{ required: true, message: '请输入字典编码', trigger: 'blur' }],
    typeName: [{ required: true, message: '请输入字典类型名称', trigger: 'blur' }],
    type: [{ required: true, message: '请输入字典类型编码', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }]
  };
  // 国际化
  const { t } = useI18n();

  // 获取表格数据
  const getList = async () => {
    try {
      loading.value = true;
      const res = await axiosRequest({
        url: API_URLS.baseSystemDict.list,
        method: 'POST',
        data: queryParams
      });
      if (res.data.operateSuccess) {
        tableData.value = res.data.baseSystemDictQueryVos;
        total.value = res.data.totals;
      }
    } catch (error) {
      console.error('获取列表失败:', error);
    } finally {
      loading.value = false;
    }
  };

  // 搜索
  const handleSearch = () => {
    queryParams.pageNum = 1;
    getList();
  };

  // 重置
  const handleReset = () => {
    queryParams.baseSystemDictQueryVo.name = '';
    queryParams.baseSystemDictQueryVo.typeName = '';
    handleSearch();
  };

  // 新增
  const handleAdd = () => {
    drawer.title = '新增字典';
    drawer.visible = true;
    drawer.type = 'add';
    Object.assign(formData, {
      dataDictId: '',
      name: '',
      value: '',
      parentValue: '',
      type: '',
      typeName: '',
      status: 1
    });
  };

  // 编辑
  const handleEdit = async (row: any) => {
    try {
      const res = await axiosRequest({
        url: API_URLS.baseSystemDict.findById,
        method: 'POST',
        data: {
          baseSystemDictQueryVo: {
            dataDictId: row.dataDictId
          }
        }
      });
      if (res.data.operateSuccess) {
        drawer.title = '编辑字典';
        drawer.visible = true;
        drawer.type = 'edit';
        Object.assign(formData, res.data.baseSystemDictQueryVo);
      }
    } catch (error) {
      console.error('获取详情失败:', error);
    }
  };

  // 详情
  const handleDetail = async (row: any) => {
    try {
      const res = await axiosRequest({
        url: API_URLS.baseSystemDict.findById,
        method: 'POST',
        data: {
          baseSystemDictQueryVo: {
            dataDictId: row.dataDictId
          }
        }
      });
      if (res.data.operateSuccess) {
        drawer.title = '字典详情';
        drawer.visible = true;
        drawer.type = 'detail';
        Object.assign(formData, res.data.baseSystemDictQueryVo);
      }
    } catch (error) {
      console.error('获取详情失败:', error);
    }
  };

  // 删除
  const handleDelete = (row: any) => {
    ElMessageBox.confirm('确认删除该字典吗？', '提示', {
      type: 'warning'
    })
      .then(async () => {
        try {
          const res = await axiosRequest({
            url: API_URLS.baseSystemDict.delete,
            method: 'POST',
            data: {
              baseSystemDictModifyVo: {
                dataDictId: row.dataDictId
              }
            }
          });
          if (res.data.operateSuccess) {
            ElMessage.success('删除成功');
            getList();
          }
        } catch (error) {
          console.error('删除失败:', error);
        }
      })
      .catch((error) => {
        console.error('删除失败:', error);
      });
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      drawer.loading = true;
      const url = formData.dataDictId ? API_URLS.baseSystemDict.update : API_URLS.baseSystemDict.save;
      const res = await axiosRequest({
        url,
        method: 'POST',
        data: {
          baseSystemDictModifyVo: formData
        }
      });
      if (res.data.operateSuccess) {
        ElMessage.success('保存成功');
        drawer.visible = false;
        getList();
      }
    } catch (error) {
      console.error('保存失败:', error);
    } finally {
      drawer.loading = false;
    }
  };

  // 状态切换
  const handleStatusChange = async (row: any, value: string | number | boolean) => {
    try {
      const updateData = {
        ...row,
        status: value
      };
      Object.assign(formData, updateData);
      await handleSubmit();
    } catch (error) {
      // 如果更新失败，回滚状态
      row.status = row.status === 1 ? 0 : 1;
      console.error('状态更新失败:', error);
    }
  };

  // 分页大小变更
  const handleSizeChange = (val: number) => {
    queryParams.pageSize = val;
    getList();
  };

  // 当前页变更
  const handlePageChange = (val: number) => {
    queryParams.pageNum = val;
    getList();
  };

  onMounted(() => {
    getList();
  });
</script>

<style lang="scss" scoped>
  .dict-container {
    padding: 16px;
    background: #fff;
    border-radius: 4px;
  }
</style>
